package com.cjg.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUCpc {
    public static void main(String[] args) {
        B a = new B();
        new Thread(()->{
            for (int i = 0; i <5 ; i++) {
                try {
                    a.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i <5 ; i++) {
                try {
                    a.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();   new Thread(()->{
            for (int i = 0; i <5 ; i++) {
                try {
                    a.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i <5 ; i++) {
                try {
                    a.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}
class B{
    private int unm=0;
    //作用域提升的锁
    Lock lock=new ReentrantLock();
    //使用condition接口
    Condition condition = lock.newCondition();
    public  void increment() throws InterruptedException {
        //开启锁
        lock.lock();
        //业务
        try {
            while (unm!=0){
                //等待
                condition.await();
            }
            unm++;
            System.out.println(Thread.currentThread().getName()+":"+unm);
            //唤醒
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭锁
            lock.unlock();
        }

    }
    public  void decrement() throws InterruptedException {
        //开启锁
        lock.lock();
        //业务
        try {
            while (unm==0){
                //等待
                condition.await();
            }
            unm--;
            System.out.println(Thread.currentThread().getName()+":"+unm);
            //唤醒
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭锁
            lock.unlock();
        }
    }
}